package com.spa.domain.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.spa.domain.entity.Trade;
import com.spa.domain.entity.UserInfo;
import com.spa.infrastructure.mapper.TradeMapperStruct;
import com.spa.infrastructure.repository.condition.TradeCondition;
import com.spa.infrastructure.repository.po.TradePO;
import com.spa.infrastructure.repository.service.TradeRepositoryService;
import com.spa.infrastructure.service.wx.result.PaySuccessResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class TradeService {

    @Autowired
    private TradeRepositoryService tradeRepositoryService;

    public Long add(PaySuccessResult result) {
        TradePO po = TradeMapperStruct.INSTANCE.command2Po(result);
        if (ObjectUtil.isNotNull(result.getPayer())) {
            po.setOpenid(result.getPayer().getOpenid());
        }
        if (ObjectUtil.isNotNull(result.getAmount())) {
            PaySuccessResult.Amount amount = result.getAmount();
            po.setTotal(amount.getTotal());
            po.setPayerTotal(amount.getPayer_total());
            po.setCurrency(amount.getCurrency());
            po.setPayerCurrency(amount.getPayer_currency());
        }
        return tradeRepositoryService.add(po);
    }

    public Trade infoByOrderCode(String orderCode) {
        LambdaQueryWrapper<TradePO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(TradePO::getOutTradeNo,orderCode);
        TradePO po = tradeRepositoryService.getOne(wrapper);
        return TradeMapperStruct.INSTANCE.po2Entity(po);
    }

    /**
     * 通过订单号批量查询交易信息
     * @param orderCodes
     * @return
     */
    public List<Trade> list(List<String> orderCodes) {
        TradeCondition condition = new TradeCondition();
        condition.setOrderCodes(orderCodes);
        return tradeRepositoryService.list(condition);
    }

}
